﻿using Dapper;
using ERPEF.Model;
using ERPService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;

namespace S4Project.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class InvOtherOutboundController : ControllerBase
    {
        private readonly inv_other_outboundService inv_Other_Outbound;
        private readonly MyDbContext myDbContext;
        public InvOtherOutboundController(MyDbContext myDb, inv_other_outboundService inv_Other_OutboundService)
        {
            myDbContext = myDb;
            inv_Other_Outbound = inv_Other_OutboundService;
        }

        //其他出库查询
        [HttpGet]
        public async Task<IActionResult> Query()
        {
            var warehouse = await inv_Other_Outbound.Query();
            if (warehouse != null)
            {
                return Ok(warehouse);
            }
            else
            {
                return NotFound("404");
            }
        }

        //出库分页
        [HttpGet]
        public ActionResult<FenYe<inv_other_outbound>> GetFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "ioo_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "inv_other_outbound  "); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<inv_other_outbound>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<inv_other_outbound> fenYe = new FenYe<inv_other_outbound>()
                {
                    OutboundsData = result,
                    Rows = row,
                };

                if (fenYe.OutboundsData.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        //其他出库删除
        [HttpDelete("{ioo_id}")]
        public async Task<IActionResult> OutboundDelete(int ioo_id)
        {
            int result = await inv_Other_Outbound.Delete(ioo_id);
            if (result > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("未找到");
            }
        }

        //查询字典--物品属性
        [HttpGet]
        public async Task<IActionResult> GetAttribute()
        {
            var dic = await inv_Other_Outbound.GetAttribute();
            var dict = dic.Where(w => w.dd_type == "type_goods").ToList();
            if (dict.Any())
            {
                return Ok(dict);
            }
            else
            {
                return NotFound("404");
            }
        }

        //查询物品名称
        [HttpGet]
        public async Task<IActionResult> GetImage(string where)
        {
            var del = await inv_Other_Outbound.GetImage();
            var data = del.Where(w => w.di_type == where).ToList();
            if (data != null)
            {
                return Ok(data);
            }
            else
            {
                return NotFound("404");
            }
        }

        //查询字典--单位
        [HttpGet]
        public async Task<IActionResult> GetUnit()
        {
            var dic = await inv_Other_Outbound.GetUnit();
            var dict = dic.Where(w => w.dd_type == "type_unit").ToList();
            if (dict.Any())
            {
                return Ok(dict);
            }
            else
            {
                return NotFound("404");
            }
        }
        //查询仓库
        [HttpGet]
        public async Task<IActionResult> GetWarehouse()
        {
            var data = await inv_Other_Outbound.GetWarehouse();
            if (data != null)
            {
                return Ok(data);
            }
            else
            {
                return NotFound("404");
            }
        }


        /// <summary>
        /// 物品出库审核
        /// </summary>
        /// <param name="ioo_id"></param>
        /// <returns></returns>
        [HttpPost("{ioo_id}")]
        public async Task<IActionResult> AuditOtherOut(int ioo_id)
        {
            // 从数据库中获取入库单
            var storage = await myDbContext.inv_other_outbound
                .FirstOrDefaultAsync(s => s.ioo_id == ioo_id);

            // 如果入库单不存在或已经被逻辑删除，则返回错误信息
            if (storage == null || storage.IsDeleted)
            {
                return NotFound("未找到对应的数据");
            }
            if (storage.ioo_audit == true)
            {
                return BadRequest("该订单已进行了出库，不能再进行审核");
            }
            try
            {

                // 检查库存是否存在
                var inventory = await myDbContext.inv_goods_inventory
                    .FirstOrDefaultAsync(i => i.igi_name == storage.ioo_item_name
                                          && i.igi_warehouse == storage.ioo_warehouse);

                if (inventory == null)
                {
                    // 如果库存记录不存在，则不进行审核，并返回特定信息
                    return Ok("审核失败，未找到对应的库存记录");
                }



                // 审核入库单
                storage.ioo_audit = true;

                // 保存更改到数据库
                await myDbContext.SaveChangesAsync();

                return Ok("审核成功，库存已更新");
            }
            catch (DbUpdateException ex)
            {
                // 如果没有找到库存记录，则返回特定的消息
                if (ex.Message.Contains("没有找到对应的库存记录"))
                {
                    return Ok("审核成功，但未找到库存记录进行更新");
                }
                return StatusCode(500, "审核失败，数据库更新异常：" + ex.Message);
            }
        }
    }
}
